package com.mashibing.test.case24.annotation.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.mashibing.test.case24.annotation.dao.BookDao;
import com.mashibing.test.case24.annotation.service.BookService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.sql.DataSource;

@Configuration
@PropertySource("classpath:com/mashibing/test/case24/db.properties")
@EnableTransactionManagement
public class TransactionConfig {
	@Value("${jdbc.driverClass}")
	private String driverClassName;
	@Value("${jdbc.jdbcUrl}")
	private String url;
	@Value("${jdbc.user}")
	private String username;
	@Value("${jdbc.password}")
	private String password;

	@Bean
	public DataSource dataSource() {
		DruidDataSource data = new DruidDataSource();
		data.setDriverClassName(driverClassName);
		data.setUrl(url);
		data.setUsername(username);
		data.setPassword(password);
		return data;
	}

	@Bean
	public JdbcTemplate jdbcTemplate(DataSource dataSource) {
		return new JdbcTemplate(dataSource);
	}

	@Bean
	public BookDao bookDao() {
		return new BookDao();
	}

	@Bean
	public BookService bookService() {
		BookDao bookDao = bookDao();
		System.out.println(bookDao);
		return new BookService();
	}

	@Bean
	public PlatformTransactionManager transactionManager(DataSource dataSource) {
		DataSourceTransactionManager dataSourceTransactionManager = new DataSourceTransactionManager(dataSource);
		//设置只读事务优化
		//dataSourceTransactionManager.setEnforceReadOnly(true);
		return dataSourceTransactionManager;
	}
}
